package base.core.exception;

import base.core.util.Utils;

import org.apache.commons.lang3.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @Description 建议使用 Throws.If(true).of(ElegantException.of(message,e));
 * @Author Pengwei
 * @CreatDate 2021/12/25 03:03
 */
@Data
@Accessors(chain = true)
public class BaseException extends RuntimeException {
    String message;

    Exception exception;

    public BaseException(String message) {
        super(message);
        this.message = message;
    }

    public BaseException(String message, Exception exception) {
        super(message, exception);
        this.message = message;
        this.exception = exception;
    }

    public static BaseException of(String message) {
        return new BaseException(message);
    }

    public static BaseException of(String message, Exception exception) {
        return new BaseException(message, exception);
    }

    /**
     * 格式化异常信息
     * (a{}a{}a,1,2,3,exception) -> a1a2a3,exception
     * @param message
     * @param objects
     * @return
     */
    public static BaseException of(String message, Object... objects) {
        if (ObjectUtils.isEmpty(objects)) {
            return new BaseException(message);
        }
        List<Object> objectList = Arrays.stream(objects).collect(Collectors.toList());
        if (objectList.get(objectList.size() - 1) instanceof Exception) {
            //除去异常后的变量
            Object[] variables = objectList.subList(0, objectList.size() - 1).toArray();
            return new BaseException(Utils.format(message, variables), (Exception) objectList.get(objectList.size() - 1));
        }
        return new BaseException(Utils.format(message,objects));
    }
}
